<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>编辑页面</title>
</head>
<body>

<script>
	// 定义试题类型与对应div的映射关系
	const questionTypeMap = {
		1: 'singleChoice',
		2: 'multipleChoice',
		3: 'panduanChoice',
		4: 'simpleChoice'
	};

	// 根据选择的类型显示或隐藏相应的div
	function toggleInputs(type) {

		console.log(type)
		// 获取所有试题类型的div
		const divs = Object.values(questionTypeMap).map(id => document.getElementById(id));

		// 隐藏所有div并移除lay-verify="required"属性
		divs.forEach(div => {
			if (div) {
				div.style.display = 'none';
				const inputs = div.querySelectorAll('input, textarea');
				inputs.forEach(input => {
					input.removeAttribute('lay-verify');
				});
			}
		});

		// 显示当前类型的div并添加lay-verify="required"属性
		const currentDiv = document.getElementById(questionTypeMap[type]);
		if (currentDiv) {
			currentDiv.style.display = 'block';
			const inputs = currentDiv.querySelectorAll('input, textarea');
			inputs.forEach(input => {
				// 排除多选题的选项E和F
				if (!['multiple_options_e', 'multiple_options_f'].includes(input.name)) {
					input.setAttribute('lay-verify', 'required');
				}
			});
		}
	}

	// 假设这是页面加载时初始化试题类型的函数
	// function initQuestionType() {
	// 	const questionType = document.querySelector('input[name="type"]:checked').value;
	// 	toggleInputs(questionType);
	// }
	//
	// // 页面加载时初始化
	// window.onload = initQuestionType;
</script>
<script type="text/html" id="form">
    <input type="hidden" name="id" value="{{= d.id }}" />
    <div class="mainBox">
        <div class="main-container">
            <div class="main-container">

				<div class="layui-form-item">
    				<label class="layui-form-label" title="类型"> <text title="必填项" style="color:red;">*</text> 类型 </label>
    				<div class="layui-input-block">
            			<input type="radio" lay-filter="type" name="type" id="type-1" value="1" title="单选题" {{#if (d.type == '1'){ }}checked="checked"{{# } }} />
						<input type="radio" lay-filter="type" name="type" id="type-2" value="2" title="多选题" {{#if (d.type == '2'){ }}checked="checked"{{# } }} />
						<input type="radio" lay-filter="type" name="type" id="type-3" value="3" title="判断题" {{#if (d.type == '3'){ }}checked="checked"{{# } }} />
						<input type="radio" lay-filter="type" name="type" id="type-4" value="4" title="简答题" {{#if (d.type == '4'){ }}checked="checked"{{# } }} />
<!--						<input type="radio" name="type" id="type-5" value="5" title="填空题" {{#if (d.type == '5'){ }}checked="checked"{{# } }} />-->
    				</div>
				</div>

				<div class="layui-form-item">
    				<label class="layui-form-label" title="题干"> <text title="必填项" style="color:red;">*</text> 题干</label>
    				<div class="layui-input-block">
            			<textarea name="title" id="title" placeholder="请输入题干" class="layui-textarea" lay-verify="required">{{=d.title}}</textarea>
    				</div>
				</div>

				<!-- 单选题 -->
				<div class="layui-form-item" id="singleChoice" style="display: none;">
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项A"> <text title="必填项" style="color:red;">*</text>选项A</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="single_options_a" id="options_a" placeholder="请输入选项A内容" class="layui-input" lay-verify="required">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项B"> <text title="必填项" style="color:red;">*</text>选项B</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="single_options_b" id="options_b" placeholder="请输入选项B内容" class="layui-input" lay-verify="required">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项C"> <text title="必填项" style="color:red;">*</text>选项C</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="single_options_c" id="options_c" placeholder="请输入选项B内容" class="layui-input" lay-verify="required">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项D"> <text title="必填项" style="color:red;">*</text>选项D</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="single_options_d" id="options_d" placeholder="请输入选项B内容" class="layui-input" lay-verify="required">
						</div>
					</div>

					<div class="layui-form-item">
						<label class="layui-form-label" title="考试名称"> <text title="必填项" style="color:red;">*</text>答案</label>

						<div class="layui-input-block">
							<input type="radio" name="single_anwser" id="anwser-1" value="A" title="A" checked="checked" />
							<input type="radio" name="single_anwser" id="anwser-2" value="B" title="B"  />
							<input type="radio" name="single_anwser" id="anwser-3" value="C" title="C"  />
							<input type="radio" name="single_anwser" id="anwser-4" value="D" title="D"  />
						</div>
					</div>
				</div>

				<!-- 多选题 -->
				<div class="layui-form-item" id="multipleChoice" style="display: none;">
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项A"> <text title="必填项" style="color:red;">*</text>选项A</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="multiple_options_a" placeholder="请输入选项A内容" class="layui-input" lay-verify="required">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项B"> <text title="必填项" style="color:red;">*</text>选项B</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="multiple_options_b" placeholder="请输入选项B内容" class="layui-input" lay-verify="required">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项C"> <text title="必填项" style="color:red;">*</text>选项C</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="multiple_options_c" placeholder="请输入选项内容" class="layui-input" lay-verify="required">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项D"> <text title="必填项" style="color:red;">*</text>选项D</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="multiple_options_d" placeholder="请输入选项内容" class="layui-input" lay-verify="required">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项E">选项E</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="multiple_options_e"  class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项F">选项F</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="multiple_options_f" class="layui-input">
						</div>
					</div>

					<div class="layui-form-item" >
						<label class="layui-form-label" title="选项"> <text title="必填项" style="color:red;">*</text>答案</label>

						<div class="layui-input-block">
							<input type="checkbox" name="multiple_anwser[]" value="A" title="A" />
							<input type="checkbox" name="multiple_anwser[]" value="B" title="B" />
							<input type="checkbox" name="multiple_anwser[]" value="C" title="C" />
							<input type="checkbox" name="multiple_anwser[]" value="D" title="D" />
							<input type="checkbox" name="multiple_anwser[]" value="E" title="E" />
							<input type="checkbox" name="multiple_anwser[]" value="F" title="F" />

						</div>
					</div>
				</div>

				<!-- 判断题 -->
				<div class="layui-form-item" id="panduanChoice" style="display: none;">
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项A"> <text title="必填项" style="color:red;">*</text>选项A</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="panduan_options_a" id="true_false_a" placeholder="请输入选项A内容" class="layui-input" lay-verify="required">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label" title="选项B"> <text title="必填项" style="color:red;">*</text>选项B</label>
						<div class="layui-input-block">
							<input autocomplete="off" type="text" name="panduan_options_b" id="true_false_b" placeholder="请输入选项B内容" class="layui-input" lay-verify="required">
						</div>
					</div>


					<div class="layui-form-item">
						<label class="layui-form-label" title="考试名称"> <text title="必填项" style="color:red;">*</text>答案</label>

						<div class="layui-input-block">
							<input type="radio" name="panduan_anwser" id="anwser-true" value="A" title="A" checked="checked" />
							<input type="radio" name="panduan_anwser" id="anwser-false" value="B" title="B"  />
						</div>
					</div>
				</div>

				<!-- 简答题 -->
				<div class="layui-form-item" id="simpleChoice" style="display: none;">
					<div class="layui-form-item">
						<label class="layui-form-label" title="答案"> <text title="必填项" style="color:red;">*</text>答案</label>
						<div class="layui-input-block">
							<textarea name="anwser" id="anwser" placeholder="请输入答案" class="layui-textarea" lay-verify="required"></textarea>
						</div>
					</div>
				</div>


				<div class="layui-form-item">
    				<label class="layui-form-label" title="分值">分值</label>
    				<div class="layui-input-block">
            			<input autocomplete="off" type="text" name="socre" id="socre" placeholder="请输入分值" value="{{=d.socre}}" class="layui-input" lay-verify="number">
    				</div>
				</div>

				<div class="layui-form-item">
    				<label class="layui-form-label" title="难度"> <text title="必填项" style="color:red;">*</text>难度</label>
    				<div class="layui-input-block">
            			<input type="radio" name="difficulty" id="difficulty-1" value="1" title="简单" {{#if (d.difficulty == '1'){ }}checked="checked"{{# } }} />
						<input type="radio" name="difficulty" id="difficulty-2" value="2" title="中等" {{#if (d.difficulty == '2'){ }}checked="checked"{{# } }} />
						<input type="radio" name="difficulty" id="difficulty-3" value="3" title="困难" {{#if (d.difficulty == '3'){ }}checked="checked"{{# } }} />
    				</div>
				</div>

				<div class="layui-form-item">
    				<label class="layui-form-label" title="分类">分类</label>
    				<div class="layui-input-block">
            			<select name="category_id" id="category_id" lay-verify="" placeholder="请选择分类">
							<option value="">请选择分类</option>
							<option value="1" {{# if(d.category_id.toString() == '1'){ }}selected="selected"{{# } }}>A分类</option>
                        </select>
    				</div>
				</div>

				<div class="layui-form-item">
    				<label class="layui-form-label" title="课程">课程</label>
    				<div class="layui-input-block">
            			<select name="course_id" id="course_id" lay-verify="" placeholder="请选择课程id">
							<option value="">请选择课程id</option>
                        </select>
    				</div>
				</div>

				<div class="layui-form-item">
    				<label class="layui-form-label" title="状态"> <text title="必填项" style="color:red;">*</text>状态</label>
    				<div class="layui-input-block">
            			<!-- 隐藏域设置开关未选中时需要传递的参数值 -->
                        <input type="hidden" name="status" id="status-0" value="0" />
                        <input type="checkbox" name="status" id="status-1" lay-skin="switch" lay-text="启用|禁用" value="1" {{# if(1 == d.status){ }}checked="checked"{{# } }} />
    				</div>
				</div>

            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="laytp-btn laytp-btn-primary laytp-btn-sm" lay-submit="" lay-filter="laytp-form">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="laytp-btn laytp-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</script>
<form class="layui-form" lay-filter="layui-form"></form>
<script>
    if(localStorage.getItem("staticDomain")){
        document.write("<link rel='stylesheet' href='" + localStorage.getItem("staticDomain") + "/component/laytp/css/laytp.css?v=" + localStorage.getItem("version") + "'>");
        document.write("<script src='" + localStorage.getItem("staticDomain") + "/component/layui/layui.js?v=" + Date.now() + "'><\/script>");
        document.write("<script src='" + localStorage.getItem("staticDomain") + "/component/laytp/layuiConfig.js?v=" + Date.now() + "'><\/script>");
    }else{
        document.write("<link rel='stylesheet' href='/static/component/laytp/css/laytp.css?v=" + localStorage.getItem("version") + "'>");
        document.write("<script src='/static/component/layui/layui.js?v=" + Date.now() + "'><\/script>");
        document.write("<script src='/static/component/laytp/layuiConfig.js?v=" + Date.now() + "'><\/script>");
    }
</script>
<script>
    layui.use(['laytp'], function () {
        let form = layui.form;
        let $ = layui.jquery;

        // 获取参数ID
        var id = facade.getUrlParam('id');
        if (!id) {
            facade.error('参数ID不能为空');
            return false;
        }

        // 定义全局变量 d，用于存储数据
        let d = {};

        // 获取数据，渲染到对应的节点上
        facade.ajax({
            route: "/admin.questions/info",
            data: { id: id },
            successAlert: false,
            showLoading: true
        }).done(function (res) {
            if (res.code === 0) {
                d = res.data; // 确保 d.category_id 和 d.course_id 在模板渲染前已赋值

                // 动态加载分类数据
                facade.ajax({
                    route: "/admin.category/index",
                    successAlert: false,
                    showLoading: true
                }).done(function (res) {
                    if (res.code === 0) {
                        let categorySelect = $('#category_id');
                        categorySelect.empty(); // 清空原有选项
                        categorySelect.append('<option value="">请选择分类</option>'); // 添加默认选项

                        // 遍历接口返回的分类数据，动态生成选项
                        res.data.forEach(function (category) {
                            let selected = d.category_id && category.id.toString() === d.category_id.toString() ? 'selected="selected"' : '';
                            categorySelect.append(`<option value="${category.id}" ${selected}>${category.name}</option>`);
                        });

                        form.render('select'); // 刷新表单组件
                    }
                });

                // 动态加载课程数据
                facade.ajax({
                    route: "/admin.course/index",
                    successAlert: false,
                    showLoading: true
                }).done(function (res) {
                    if (res.code === 0) {
                        let courseSelect = $('#course_id');
                        courseSelect.empty(); // 清空原有选项
                        courseSelect.append('<option value="">请选择课程id</option>'); // 添加默认选项

                        // 遍历接口返回的课程数据，动态生成选项
                        res.data.forEach(function (course) {
                            let selected = d.course_id && course.id.toString() === d.course_id.toString() ? 'selected="selected"' : '';
                            courseSelect.append(`<option value="${course.id}" ${selected}>${course.name}</option>`);
                        });

                        form.render('select'); // 刷新表单组件
                    }
                });

                // 渲染表单
                layui.laytpl($("#form").html()).render(d, function (string) {
                    $("form").html(string);
                    layui.laytpForm.render();

                    // 根据后端返回的试题类型显示对应的div
                    toggleInputs(d.type);

                    // 根据试题类型回显数据
                    if (d.type == 1) {
                        // 单选题
                        $('#options_a').val(d.option_a);
                        $('#options_b').val(d.option_b);
                        $('#options_c').val(d.option_c);
                        $('#options_d').val(d.option_d);
                        $(`input[name="single_anwser"][value="${d.anwser}"]`).prop('checked', true);
                    } else if (d.type == 2) {
                        // 多选题
                        $('input[name="multiple_options_a"]').val(d.option_a);
                        $('input[name="multiple_options_b"]').val(d.option_b);
                        $('input[name="multiple_options_c"]').val(d.option_c);
                        $('input[name="multiple_options_d"]').val(d.option_d);
                        $('input[name="multiple_options_e"]').val(d.option_e);
                        $('input[name="multiple_options_f"]').val(d.option_f);
                        d.anwser.split(',').forEach(function (ans) {
                            $(`input[name="multiple_anwser[]"][value="${ans}"]`).prop('checked', true);
                        });
                    } else if (d.type == 3) {
                        // 判断题
                        $('#true_false_a').val(d.option_a);
                        $('#true_false_b').val(d.option_b);
                        $(`input[name="panduan_anwser"][value="${d.anwser}"]`).prop('checked', true);
                    } else if (d.type == 4) {
                        // 简答题
                        $('#anwser').val(d.anwser);
                    }

                    form.render(); // 重新渲染表单以确保回显生效
                });
            }
        });

        form.on('submit(laytp-form)', function (data) {
            // 移除隐藏的div中的input和textarea元素
            const divs = Object.values(questionTypeMap).map(id => document.getElementById(id));
            divs.forEach(div => {
                if (div && div.style.display === 'none') {
                    const inputs = div.querySelectorAll('input, textarea');
                    inputs.forEach(input => {
                        // 确保移除的是当前div中的元素
                        if (input.parentNode === div) {
                            input.remove();
                        }
                    });
                }
            });

            var btnAnim = layui.button.load({ elem: $(this) });
            try {
                data = facade.setEditorField(data);
            } catch (e) {
                facade.error(e);
                return false;
            }
            facade.ajax({
                route: '/admin.questions/edit',
                data: data.field
            }).done(function (res) {
                if (res.code === 0) {
                    parent.layui.layer.close(parent.layui.layer.getFrameIndex(window.name)); // 关闭当前页
                    parent.layui.table.reloadData("laytp-table");
                }
                btnAnim.stop();
            }).fail(function () {
                btnAnim.stop();
            });
            return false;
        });
    });
</script>
</body>
</html>